<?php

namespace Common\Model;
use Curl\Curl;
/**
 * 环信业务处理模块
 */
class HuanxinLogic {

  private $host = 'https://a1.easemob.com';

  /**
   *  获取环信token
   */
  public function getToken($force = false){
    $token = S('huanxin_token');
    //如果强制获取，或者用户token已经失效,则重新获取token
    if($force || !$token){
      $curl = new Curl;
      $curl->setHeader('Content-Type', 'application/json');
      $res = $curl->post($this->host.'/'.C("HUANXIN_org_name").'/'.C("HUANXIN_app_name").'/token',[
          'grant_type'  =>'client_credentials',
          'client_id' =>C("HUANXIN_client_id"),
          'client_secret' =>C('HUANXIN_client_secret'),
        ]);
      if(!empty($res->access_token) && !empty($res->expires_in) && !empty($res->application)){
        //缓存tokne
        S('huanxin_token', $res->access_token, $res->expires_in-3 );
      }
      return $res->access_token;
    }else{
      return $token;
    }
  }

  /**
   * 添加120端用户
   */
  public function addCarUser($userId){
    $this->addUser( C("HUANXIN_CAR_USER_PREFIX").$userId );
  }

  /**
   * 添加医院端用户
   */
  public function addHospitalUser($userId){
    $this->addUser( C("HUANXIN_HOSPITAL_USER_PREFIX").$userId );
  }

  /**
   *  添加用户动作
   */
  private function addUser($id){
    $curl = new Curl;
    $curl->setHeader('Content-Type','application/json');
    $curl->setHeader('Authorization','Bearer '.$this->getToken());
    $res = $curl->post($this->host.'/'.C("HUANXIN_org_name").'/'.C("HUANXIN_app_name").'/users',[
        'username'  =>$id,
        'password'  =>C("HUANXIN_DEFAULT_PASSWORD"),
      ]);
  }

}